import {designPage, onMounted, reactive} from "@peryl/react-compose";
import {$dialog, $message, $notice} from "plain-design";
import '../resume/resume-template-page.scss';
import {ResumeIcons} from "../resume/ResumeIcons";
import {usePageService} from "../../modules/micro/usePageService";
import {iPageCardStarterOption, PageCardStarter} from "../components/PageCardStarter";
import {PageCardList} from "../components/PageCardList";
import {iCodeGeneratorRecord} from "./code-generator.utils";
import {http} from "../../modules/plain-design/http";

export default designPage(() => {

  const { nav, onBack } = usePageService();

  const state = reactive({
    codeGeneratorRecordData: [] as iCodeGeneratorRecord[]
  });

  const handler = {
    reloadData: async () => {
      const data = await http.post<{ list: iCodeGeneratorRecord[] }>('/code_gen/list', { all: true });
      state.codeGeneratorRecordData = data.list;
    },
    handleEdit: (codeGeneratorRecord: iCodeGeneratorRecord) => {
      nav.push('/react-base/code-generator/code-generator-edit-page', { codeGeneratorRecord });
    },
    handleCopy: async (codeGeneratorRecord: iCodeGeneratorRecord) => {
      await $dialog.confirm(`复制页面？`);
      const { id, createdAt, createdBy, updatedAt, updatedBy, ...newRecord } = codeGeneratorRecord;
      await http.post('/code_gen/insert', { row: newRecord });
      await handler.reloadData();
    },
    handleDelete: async (codeGeneratorRecord: iCodeGeneratorRecord) => {
      await $dialog.confirm(`删除页面？`);
      await http.post('/code_gen/delete', { id: codeGeneratorRecord.id });
      await handler.reloadData();
      $message.success('已删除');
    },
  };

  const starterOptions: iPageCardStarterOption[] = [
    {
      label: '创建页面配置', icon: ResumeIcons.file_add, handler: () => {
        nav.push('/react-base/code-generator/code-generator-edit-page', { codeGeneratorRecord: null });
      }
    },
    {
      label: '导入配置文件', icon: ResumeIcons.file_upload_lie, handler: () => {
        $notice.warn('未完成');
      }
    },
    {
      label: '导入配置数据', icon: ResumeIcons.file_edit_line, handler: () => {
        $notice.warn('未完成');
      }
    },
  ];

  const starter = () => (<PageCardStarter title="AI生成页面" starterOptions={starterOptions}/>);

  onBack(async () => {
    await handler.reloadData();
  });

  onMounted(async () => {
    // starterOptions[0].handler();
    await handler.reloadData();
  });

  return () => (
    <div className="resume-template-page">
      <PageCardList
        data={[starter, ...state.codeGeneratorRecordData]}
        aspectRatio="4 / 3"
        editButtonText="编辑页面配置"
        copyButtonText="拷贝页面配置"
        showEditButton
        showCopyButton
        showDeleteButton
        onEdit={handler.handleEdit}
        onCopy={handler.handleCopy}
        onDelete={handler.handleDelete}
      />
    </div>
  );

});
